package servlet;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@WebServlet("/UpdateUserServlet")
@MultipartConfig(maxFileSize = 1024*1024*2) //2MB
public class UpdateUserServlet extends HttpServlet {
    //允许的图片类型
    private final String ALLOW_IMG_TYPE="image/png;image/jpeg;image/gif";


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解码方式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String opr=request.getParameter("opr");
        HttpSession session= request.getSession();
        PrintWriter out= response.getWriter();

        UserService userService=new UserServiceImpl();

        if (opr.equals("updateImg")){
            //获取存储到服务器的路径
            String uploadFilePath=request.getSession().getServletContext().getRealPath("/upload");
            String message="";
            try{
                //如果上传的路径不存在，则新建
                File file=new File(uploadFilePath);
                if (!file.exists()){
                    file.mkdir();
                }
                //获取part:根据name获取
                Part part=request.getPart("fileField");
                //获取上传文件的类型
                String contentType=part.getContentType();
                //将分割后的数组转成集合List类型
                List<String> allowTypes = Arrays.asList(ALLOW_IMG_TYPE.split(";"));
                //判断类型是否在允许的范围内
                if ( !(contentType==null || (contentType.trim()).equals(""))
                        &&  allowTypes.contains(contentType)){
                    //提取文件名
                    String fileName=extractFileName(part);
                    //获取后缀名
                    String suffix=getSuffix(fileName);
                    //为了避免名字冲突，使用"UUID+后缀"(获取到一个新的文件名)
                    //68784616sq-q56-54845-565-65.jpg
                    String newFileName= UUID.randomUUID().toString().replace("-","")+suffix;

                    //将新的文件名写入指定的服务器路径
                    String location=uploadFilePath+File.separator+newFileName;
                    //写入
                    part.write(location);

                    //更新数据库
                    User user =(User) session.getAttribute("user");
                    user.setImage("upload/"+newFileName);
                    int i=userService.updateUserImage(user);
                    if (i>0){
                        session.setAttribute("user",user);
                        //刷新
                        response.sendRedirect(request.getHeader("Referer"));
                    }else {
                        out.println("<script>");
                        out.println("alert('头像更新失败！')");
                        out.println("window.history.back(-1)");
                        out.println("</script>");
                    }



                }else {
                    //文件类型不正确
                    out.println("<script>");
                    out.println("alert('上传失败！文件类型错误！')");
                    out.println("window.history.back(-1)");
                    out.println("</script>");
                }


            }catch (IllegalStateException e){
                //文件类型不正确
                out.println("<script>");
                out.println("alert('上传失败！文件大小必须在2MB以内！')");
                out.println("window.history.back(-1)");
                out.println("</script>");
            }catch (Exception e){
                e.printStackTrace();
            }
            //刷新
            out.flush();
            //关闭
            out.close();


        }

    }


    //从http的header头部提取文件的名称：(截取文件名)
    private String extractFileName(Part part){
        //获取浏览器头部信息
        String contentDisp=part.getHeader("content-disposition");
        String [] items=contentDisp.split(";");
        //filename="1.png";info="S454C5DS";
        for (String s:items){
            if (s.trim().startsWith("filename")){
                return s.substring(s.indexOf("=")+2,s.length()-1);
            }
        }
        return "";
    }

    //获取文件后缀名的方法
    private String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
